package com.nhim.cms.util;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.nhim.cms.dao.CustomWidgetInstanceDAO;
import com.nhim.cms.domain.CustomWidgetInstance;
import com.nhim.cms.domain.CustomWidgetPropertyValue;

@Service
public class CustomWidgetInstanceManager {
	@Autowired
	private CustomWidgetInstanceDAO customWidgetInstanceDAO;
	@Autowired
	CustomWidgetPropertyValueManager customWidgetPropertyValueManager;

	@PostConstruct
	public void init() throws Exception {
	}

	@PreDestroy
	public void destroy() {
	}
	@Transactional(readOnly = true)
	public List<CustomWidgetInstance> findAll() {
		return customWidgetInstanceDAO.findAll();
	}
	@Transactional(readOnly = true)
	public List<CustomWidgetInstance> getByCustomWidgetId(Integer widgetId)
	{
		return customWidgetInstanceDAO.getByCustomWidgetId(widgetId);
	}
	@Transactional(readOnly = true)
	public CustomWidgetInstance findById(Integer id)
	{
		return customWidgetInstanceDAO.findById(id);
	}
	
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public CustomWidgetInstance saveOrUpdate(CustomWidgetInstance entity)
			throws Exception {

		CustomWidgetInstance saveCWG = customWidgetInstanceDAO.saveOrUpdate(entity);
		return saveCWG;

	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public Boolean delete(Integer id) throws Exception {
		CustomWidgetInstance customWidgetInstance = customWidgetInstanceDAO.findById(id);
		if (customWidgetInstance != null) {
			beforeDelete(id);
			customWidgetInstanceDAO.delete(customWidgetInstance);
			return true;
		}
		return false;
	}
	
	public static CustomWidgetInstanceManager getFromApplicationContext(
			ApplicationContext ctx) {
		return (CustomWidgetInstanceManager) ctx
				.getBean(CustomWidgetInstanceManager.class);
	}
	
	/*-----------------Region Private Method ------------------------------*/
	private void beforeDelete(Integer id) throws Exception {
		try {
			List<CustomWidgetPropertyValue> results = customWidgetPropertyValueManager.findByCustomWidgetInstanceId(id);
			for (CustomWidgetPropertyValue pProperty : results) {
				customWidgetPropertyValueManager.delete(pProperty);
			}
		} catch (Exception e) {
			throw e;
		}

	}
}
